package cn.b.sky.mes.em.service.impl;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import cn.b.sky.mes.em.model.EquipmentAttach;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import cn.b.sky.mes.em.dao.EquipmentAttachDao;
import cn.b.sky.mes.em.dao.EquipmentDao;
import cn.b.sky.mes.em.model.Equipment;
import cn.b.sky.mes.em.model.condition.EquipmentCondition;
import cn.b.sky.mes.em.service.EquipmentService;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.utils.DatabaseUtils;
import cn.b.sky.common.utils.FTPUtils;
import cn.b.sky.common.utils.SkyFileUtils;
import cn.b.sky.common.utils.SpringBeanUtil;
import cn.b.sky.i18n.utils.LocaleResourceBundle;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.model.Attachment;
import cn.b.sky.user.service.AttachmentService;

/**
 * <strong>Title : EquipmentServiceImpl.java<br>
 * </strong> <strong>Package : cn.b.sky.mes.em.service.impl<br>
 * </strong> <strong>Description : </strong>@类注释说明写在此处@<br>
 * <strong>Create on : 2015年11月3日 上午10:09:44<br>
 * </strong>
 * <p>
 *  
 * @author dapeng.li<br>
 * @version <strong>v1.0.0</strong><br>
 *          <br>
 *          <strong>修改历史:</strong><br>
 *          修改人 | 修改日期 | 修改描述<br>
 *          -------------------------------------------<br>
 *          <br>
 *          <br>
 */
@Service("equipmentService")
public class EquipmentServiceImpl implements EquipmentService {

  private static final Logger LOGGER = LoggerFactory.getLogger(EquipmentServiceImpl.class);

  @Resource
  EquipmentDao equipmentDao;

  @Resource
  EquipmentAttachDao equipmentAttachDao;

  @Resource
  AttachmentService attachmentService;

  @Override
  public List<Equipment> selectEquipmentList(EquipmentCondition condition) {
    if (condition == null) {
      condition = new EquipmentCondition();
    }
    if (StringUtils.isBlank(condition.getOrderField())) {
      condition.setOrderField("CreateDateTime");
    }
    return equipmentDao.selectEquipmentList(condition);
  }

  @Override
  public int selectEquipmentCount(EquipmentCondition condition) {
    if (condition == null) {
      condition = new EquipmentCondition();
    }
    return equipmentDao.selectEquipmentCount(condition);
  }

  @Override
  public void updateEquipment(Equipment equipment) {
    if (equipment != null && !StringUtils.isBlank(equipment.getEquipmentCode())) {
      equipmentDao.updateEquipment(equipment);
    } else {
      return;
    }

  }

  @Override
  public void saveEquipment(Equipment equipment) {
    if (equipment != null && !StringUtils.isBlank(equipment.getEquipmentCode())) {
      equipmentDao.saveEquipment(equipment);
    } else {
      return;
    }

  }

  @Override
  public BatchJobReport deleteEquipment(String equipmentCode, String siteCode) {
    if (!StringUtils.isBlank(equipmentCode)) {
      String message = equipmentCode;
      String cause = "";
      boolean success = true;
      try {
        equipmentAttachDao.deleteEquipmentAttach(equipmentCode, siteCode);
        equipmentDao.deleteEquipment(equipmentCode, siteCode);
      } catch (Exception e) {
        LOGGER.error("{}", e);
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        success = false;
        String errorMsg = e.getMessage();
        if (DatabaseUtils.isConstraintsError(e.getMessage())) {
          // 外键删除已存在提示
          errorMsg = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
              SecurityContextUtil.getLanguageCode(), "dataBaseOperationPkFail.M")
              + LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
                  SecurityContextUtil.getLanguageCode(), "notDelete.M");
        }
        cause = errorMsg;
      }
      return new BatchJobReport(message, cause, success);
    } else {
      return new BatchJobReport("", "equipment is null", false);
    }
  }

  @Override
  public Equipment getEquipment(String equipmentCode, String siteCode) {
    if (StringUtils.isBlank(equipmentCode) || StringUtils.isBlank(siteCode)) {
      return null;
    } else {
      return equipmentDao.getEquipment(equipmentCode, siteCode);
    }
  }

  @Override
  public void saveEquipmentAttachment(EquipmentAttach equipmentAttach, MultipartFile file) {
    if (equipmentAttach != null && !StringUtils.isBlank(equipmentAttach.getSiteCode())) {
      String filePath = SkyFileUtils.buildFilePath("equipment");
      String fileName = file.getOriginalFilename();
      String md5 = "";
      try {
        md5 = SkyFileUtils.getMD5String(file.getBytes());
      } catch (IOException e) {
        LOGGER.error("{}", e);
      }
      Attachment att = attachmentService.selectAttachmentByHashCode(equipmentAttach.getSiteCode(), md5);
      String saveName = UUID.randomUUID().toString();
      // MD5校验，映射文件
      if (att != null) {
        att.setRefCount(att.getRefCount() + 1);
        attachmentService.updateAttachmentRefCount(att);
        equipmentAttach.setAttachmentCode(att.getAttachmentCode());
        equipmentAttach.setFileSize(att.getFileSize());
        equipmentAttach.setFileName(fileName);
        equipmentAttach.setSavePath(att.getSavePath());
      } else {
        String newFileName = SkyFileUtils.renameFileName(fileName, saveName);
        FTPUtils ftpUtils = (FTPUtils) SpringBeanUtil.getBean("ftpUtils");
        String savePath = ftpUtils.uploadMultipartFiles(file, filePath, newFileName);
        Long size = file.getSize();
        equipmentAttach.setAttachmentCode(saveName);
        equipmentAttach.setFileSize(size);
        equipmentAttach.setSavePath(savePath);
        equipmentAttach.setFileName(fileName);
        att = new Attachment(saveName, savePath, fileName, size, md5, 1);
        att.setSiteCode(equipmentAttach.getSiteCode());
        attachmentService.insertAttachment(att);
      }
    }

  }

  @Override
  public void saveOrUpdateEquipment(Equipment equipment, String id,MultipartFile file) {
    if(!StringUtils.isBlank(file.getOriginalFilename())){
      String filePath = SkyFileUtils.buildFilePath("equipment");
      String fileName = file.getOriginalFilename();
      String md5 = "";
      try {
        md5 = SkyFileUtils.getMD5String(file.getBytes());
      } catch (IOException e) {
        LOGGER.error("{}", e);
      }
      Attachment att = attachmentService.selectAttachmentByHashCode(equipment.getSiteCode(), md5);      
      if (att != null) {
        att.setRefCount(att.getRefCount() + 1);
        attachmentService.updateAttachmentRefCount(att);
        equipment.setPictureAttachmentCode(att.getAttachmentCode());
      }else {
        String saveName = UUID.randomUUID().toString();
        String newFileName = SkyFileUtils.renameFileName(fileName, saveName);
        FTPUtils ftpUtils = (FTPUtils) SpringBeanUtil.getBean("ftpUtils");
        String savePath = ftpUtils.uploadMultipartFiles(file, filePath, newFileName);
        Long size = file.getSize();
        att = new Attachment(saveName, savePath, fileName, size, md5, 1);
        att.setSiteCode(equipment.getSiteCode());
        attachmentService.insertAttachment(att);
        equipment.setPictureAttachmentCode(saveName);
      }     
    }    
    if (StringUtils.isBlank(id)) {
      this.saveEquipment(equipment);
    } else {
      this.updateEquipment(equipment);
      equipmentAttachDao.deleteEquipmentAttach(equipment.getEquipmentCode(), equipment.getSiteCode());
    }
    List<EquipmentAttach> attachList = equipment.getEquipmentAttachList();
    String equipmentCode = equipment.getEquipmentCode();
    String siteCode = equipment.getSiteCode();
    for (EquipmentAttach attach : attachList) {
      if (StringUtils.isBlank(attach.getAttachmentCode())) {
        continue;
      }
      attach.setSiteCode(siteCode);
      attach.setEquipmentCode(equipmentCode);
      equipmentAttachDao.insertEquipmentAttach(attach);
    }
  }

  @Override
  public List<Equipment> selectEquipmentListForSuggest(EquipmentCondition condition) {
    return equipmentDao.selectEquipmentListForSuggest(condition);
  }

}
